//引入模型
const createModel = require('../mongodb/createModel')

//建立模型schema
const schema = {
  username: String,
  password: String,
  phoneNum: String,
  address: String,
  createTime: {
    type: Date,
    default: Date.now
  }
}

//创建表，集合
const regModel = createModel('registers', schema)

const handleReg = (params) => {
  return new Promise((resolve, reject) => {
    //console.log('参数params', params)
    //查询用户名和手机号码是否已存在
    regModel.find({"$or":[{username: params.username}, {phoneNum: params.phoneNum}]}, (err, docs) => {
      if(docs && docs.length > 0){
        let message = ''
        if(docs[0].username === params.username){
          message = '用户名已存在'
        }else if(docs[0].phoneNum === params.phoneNum){
          message = '该手机号已注册'
        }
        resolve({
          status: 1,
          code: 500,
          message: message
        })
      }else{ //新用户，加入数据库
        //save(callback)保存一条数据，与create,find等方法不一样，参数是function，使用方法是链式调用：new 集合模型(数据).save(function)
        new regModel(params).save((err, docs) => {
          if(!err){
            resolve({
              status: 1,
              ...docs
            })
          }else{
            reject({
              status: 0
            })
          }
        })
      }
    })
  })
}

const handleLogin = (params) => {
  return new Promise((resolve, reject) => {
    regModel.findOne({username: params.username}, (err, docs) => {
      if(docs && docs.password === params.password) {
        resolve({
          status: 1,
          code: 200,
          message: '登录成功'
        })
      }else{
        //console.log('找不到该用户名或密码不正确')
        resolve({
          status: 1,
          code: 500,
          message: '用户名或密码不正确'
        })
      }
    })
  })
}

module.exports = {
  handleReg,
  handleLogin
}
